import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.User.dept;
import org.example.User.emp;
import org.example.dao.DeptDao;
import org.example.dao.DeptDao;
import org.example.dao.EmpDao;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;

public class mybatis {
    public static void main(String[] args) throws IOException {
        // 1. 加载MyBatis配置，获取SqlSessionFactory
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

        // 2. 获取SqlSession和EmpDao实例
        try (SqlSession session = factory.openSession(true)) { // 自动提交事务
            EmpDao empDao = session.getMapper(EmpDao.class);

            // 测试g. 新增员工
            emp newEmp = new emp();
            newEmp.setName("赵六");
            newEmp.setSalary(BigDecimal.valueOf(7500.0));
            newEmp.setDeptId(2);
           empDao.add(newEmp);
            System.out.println("新增员工ID：" + newEmp.getId());

            // 测试d. 查找一个员工
            emp emp = empDao.findById(newEmp.getId());
            System.out.println("查询新增员工：" + emp.getName() + "，工资：" + emp.getSalary());

            // 测试c. 修改员工
            emp.setSalary(BigDecimal.valueOf(8200.0));
            int updateRows = empDao.update(emp);
            System.out.println("修改成功？" + (updateRows > 0));

            // 测试f. 按名字模糊查询
            List<emp> likeList = empDao.findByNameLike("六");
            System.out.println("名字含'六'的员工数：" + likeList.size());

            // 测试a. 查找所有员工及部门名称
            List<emp> allList = empDao.findAllWithDeptName();
            System.out.println("所有员工及部门：");
            allList.forEach(e -> System.out.println(e.getName() + " - " + e.getDeptName()));

            // 测试b. 查找工资最高员工
            emp highest = empDao.findHighestSalaryEmp();
            System.out.println("工资最高：" + highest.getName() + "，" + highest.getSalary());

            // 测试e. 根据ID删除员工
            int deleteRows = empDao.deleteById(newEmp.getId());
            System.out.println("删除成功？" + (deleteRows > 0));
        }
    }
}